/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2024-05-27 11:11:36
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2024-08-21 15:57:52
 * @FilePath: /vue3-uniapp/src/store/modules/user.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import { store } from '@/store';
import { getCurrentPage, getCurrentRoute } from '@/utils/route';
import type { RouteOption } from '@/typings/declaration/uvUi';
import { notifyAuthChange } from '@/plugins/hook';
import { readMyInfo, updateRole } from '@/api/my';
import type {
    MyInfoDetail,
    RoleGroupVo,
    UserAreaVo,
    DepartmentVo,
    CurrentRole
} from '@/typings/api/my';
import { useStorage } from '@/service/useStorage';
import { getStaticImage } from '@/utils/index';

export const useUserStore = defineStore('user', () => {
    const {
        getAccessTokenSync,
        setAccessToken,
        removeAccessToken,
        setUserInfo: setUserInfoCache,
        removeUserInfo,
        getCurrentGridSync,
        setCurrentGrid,
        getCurrentDeptSync,
        setCurrentDept
    } = useStorage();

    // const localUserInfo = getLocaUserInfo();
    const token = ref<string>(getAccessTokenSync() || '');
    const hasVaildToken = ref<boolean | null>(null); // 用这个标识来判断是否token有效，因为userInfo和token都是可能过期的, null标识未初始化，true表示token有效，false表示token无效但已鉴定过token
    const backRouteConfig = ref<RouteOption>();
    const userInfo = ref<MyInfoDetail>();
    const roleList = ref<
        {
            value: number;
            label: string;
            data: RoleGroupVo;
        }[]
    >([]);
    const roleAreaList = ref<
        {
            value: string;
            label: string;
            data: UserAreaVo;
        }[]
    >([]);
    const roleDeptList = ref<
        {
            value: number;
            label: string;
            data: DepartmentVo;
        }[]
    >([]);
    const currentRole = ref<CurrentRole>();
    const currentRoleId = ref<number>();
    const currentUserArea = ref<UserAreaVo>();
    const currentUserDept = ref<DepartmentVo>();
    const currentAreaCode = ref('');
    const currentAreaLevel = ref<number>();
    const currentDeptId = ref<number>();
    const roleType = ref<'area' | 'depart' | ''>('');
    const grid = ref('');

    const roleFunctions = ref([
        {
            title: 'E眼待审',
            img: getStaticImage(`/tabbar/function/eeye_audit.png`),
            auth: [3, 17, 18],
            route: {
                url: '/packageFunc/pages/eEye/AuditList/index'
            }
        },
        {
            title: '辖区事件汇总',
            img: getStaticImage(`/tabbar/function/important_event.png`),
            auth: [2, 4, 6],
            route: {
                url: '/packageCommon/pages/event-summary/index/index'
            }
        },
        // {
        //     title: "重大事件",
        //     img: getStaticImage(`/tabbar/function/important_event.png`),
        //     auth: [2, 4, 6],
        // },
        // {
        //     title: "工作考评",
        //     img: getStaticImage(`/tabbar/function/work_evaluation.png`),
        //     auth: [2, 4, 6],
        // },
        {
            title: '党建资讯',
            img: getStaticImage(`/tabbar/function/problem_report.png`),
            auth: [8, 13]
        },
        {
            title: '红色学堂',
            img: getStaticImage(`/tabbar/function/problem_report.png`),
            auth: [8, 13]
        },
        {
            title: '党员大会',
            img: getStaticImage(`/tabbar/function/problem_report.png`),
            auth: [8, 13]
        },
        {
            title: '廉政教育',
            img: getStaticImage(`/tabbar/function/problem_report.png`),
            auth: [8, 13]
        },
        {
            title: '数据分析',
            img: getStaticImage(`/tabbar/function/my_performance.png`),
            auth: [3, 5, 7],
            route: {
                url: '/packageInfoInput/pages/data-analysis/index/index'
            }
        },
        {
            title: '处置中心',
            img: getStaticImage(`/tabbar/function/excute_center.png`),
            auth: [3, 5, 7]
        },
        {
            title: '事件动态',
            img: getStaticImage(`/tabbar/function/event_status.png`),
            auth: [3, 5, 7]
        },
        {
            title: '群众满意度',
            img: getStaticImage(`/tabbar/function/people_satisfaction.png`),
            auth: [3, 5, 7]
            // auth: [2, 3, 4, 5, 6, 7],
        },
        {
            title: '巡查网格',
            img: getStaticImage(`/tabbar/function/inspection_grid.png`),
            route: {
                url: '/packageCommon/pages/inspectGrid/list/index'
            },
            auth: [9]
        },
        {
            title: '督查指导',
            img: getStaticImage(`/tabbar/function/supervision_guidance.png`),
            route: {
                url: '/packageCommon/pages/supervisionGuidance/list/index'
            },
            auth: [9]
        },
        {
            title: '网格会议',
            img: getStaticImage(`/tabbar/function/grid_meeting.png`),
            route: {
                url: '/packageCommon/pages/gridMeeting/list/index'
            },
            auth: [9]
        },
        {
            title: '重点监督',
            img: getStaticImage(`/tabbar/function/important_supervise.png`),
            route: {
                url: '/packageCommon/pages/importantSupervision/list/index'
            },
            auth: [9]
        },
        {
            title: '基础信息',
            img: getStaticImage(`/tabbar/function/base_info.png`),
            route: {
                url: '/packageInfoInput/pages/index/index'
            },
            auth: [3, 5, 7, 10]
        },
        // {
        //     title: "社会稳定",
        //     img: getStaticImage(`/tabbar/function/society_stable.png`),
        //     route: {
        //         url: "/packageCommon/pages/socialStability/index/index",
        //     },
        //     auth: [10],
        // },
        {
            title: '重点人群',
            img: getStaticImage(`/tabbar/function/import_people.png`),
            route: {
                url: '/pages/importantPeople/index/index'
            },
            auth: [10]
        },
        {
            title: '矛盾排查',
            img: getStaticImage(`/tabbar/function/conflict_investigation.png`),
            route: {
                url: '/packageCommon/pages/conflictCheck/list/index'
            },
            auth: [10]
        },
        {
            title: '走访工作',
            img: getStaticImage(`/tabbar/function/visit_work.png`),
            auth: [10],
            route: {
                url: '/packageCommon/pages/gridManager/interview/index'
            }
        },
        {
            title: '脱贫成果',
            img: getStaticImage(`/tabbar/function/outpoverty_result.png`),
            auth: [10]
        },
        {
            title: '我的绩效',
            img: getStaticImage(`/tabbar/function/my_performance.png`),
            route: {
                url: '/packageCommon/pages/myPerformance/list/index'
            },
            auth: [10, 11]
        },
        {
            title: '廉情直报',
            img: getStaticImage(`/tabbar/function/important_event.png`),
            auth: [8, 10, 11],
            route: {
                url: '/packageUser/pages/integrityMatters/EventList/index'
            }
        }
        // {
        //     title: "廉情讯息",
        //     img: getStaticImage(`/tabbar/function/event_status.png`),
        //     auth: [11],
        //     point: undefined,
        //     route: {
        //         url: "/packageUser/pages/integrityMatters/MessageList/index",
        //     },
        // }
    ]);

    const functions = ref([
        {
            title: '交办任务',
            img: getStaticImage(`/tabbar/function/my_task.png`),
            auth: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18],
            route: {
                url: '/packageUser/pages/task/MyTaskList/index'
            }
        },
        {
            title: '巡查走访',
            img: getStaticImage(`/tabbar/function/inspection_visiting.png`),
            auth: [3, 5, 7, 8, 10, 11],
            route: {
                url: '/packageUser/pages/inspection/InspectionList/index'
            }
        },
        // {
        //     title: "问题上报",
        //     img: "/static/images/tabbar/function/problem_report.png",
        //     auth: [10, 11],
        //     route: {
        //         url: "/pages/problemReport/edit/index",
        //     },
        // },
        {
            title: '工作记录',
            img: getStaticImage(`/tabbar/function/work_summary.png`),
            auth: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
            route: {
                url: '/packageCommon/pages/workRecords/list/index'
            }
        },
        // {
        //     title: "疫情防控",
        //     img: getStaticImage(`/tabbar/function/epidemic_prevention.png`),
        // },
        {
            title: '网格信息',
            img: getStaticImage(`/tabbar/function/grid_info.png`),
            auth: [10, 11],
            route: {
                url: '/packageCommon/pages/grid/info/index'
            }
        },
        // {
        //     title: "通讯录",
        //     img: getStaticImage(`/tabbar/function/contacts.png`),
        //     auth: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
        //     route:{
        //         url: "/packageCommon/pages/address/index/index",
        //     }
        // },
        // {
        //     title: "党建工作",
        //     img: getStaticImage(`/tabbar/function/party_work.png`),
        //     auth: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
        //     route: {
        //         url: "/packageCommon/pages/partyWork/index/index",
        //     }
        // },
        {
            title: '常见问题',
            img: getStaticImage(`/tabbar/function/common_questions.png`),
            auth: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
            route: {
                url: '/packageCommon/pages/common-problem/index'
            }
        }
        // {
        //     title: "专项指挥",
        //     img: getStaticImage(`/tabbar/function/special_command.png`),
        //     auth: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13],
        //     route: {
        //         url: "/packageCommon/pages/special-command/index",
        //     },
        // },
    ]);

    // 设置登录后跳转路由并前往登录
    const createBackRouteOptionAndGoLogin = () => {
        const currentRoute = getCurrentRoute();
        if (currentRoute.indexOf('/pages/auth/LoginView/LoginView') === -1) {
            uni.$uv.route({
                type: 'reLaunch',
                url: '/pages/auth/LoginView/LoginView'
            });
        }
        const page = getCurrentPage();
        // 重定向不能是登录页
        const route: RouteOption = {
            type: 'redirectTo',
            url: `${currentRoute === '/pages/auth/LoginView/LoginView' ? 'pages/tabbar/HomeView/HomeView' : currentRoute}`,
            params: page.options
        };
        if (
            [
                '/pages/tabbar/AreaOrderList/AreaOrderList',
                '/pages/tabbar/DepartmentOrderList/DepartmentOrderList',
                '/pages/tabbar/HomeView/HomeView',
                '/pages/tabbar/MineView/MineView',
                '/pages/tabbar/MyOrderList/MyOrderList',
                '/pages/tabbar/TodoOrderList/TodoOrderList'
            ].includes(currentRoute)
        ) {
            route.type = 'switchTab';
        }
        backRouteConfig.value = route;
    };

    const useBackRouteConfig = () => {
        let route = backRouteConfig.value;
        if (
            !token.value ||
            !route ||
            route.url === '/pages/auth/LoginView/LoginView'
        ) {
            route = {
                type: 'switchTab',
                url: '/pages/tabbar/HomeView/HomeView'
            };
        }
        backRouteConfig.value = undefined;
        uni.$uv.route(route);
    };

    const login = (tk: string) => {
        token.value = tk;
        setAccessToken(tk);
        notifyAuthChange('login');
        return Promise.resolve();
    };

    const setUserInfo = (data: MyInfoDetail) => {
        setUserInfoCache(data);
        userInfo.value = data;
        if (
            userInfo.value.roleGroupList &&
            userInfo.value.roleGroupList.length > 0
        ) {
            roleList.value = userInfo.value.roleGroupList.map((item) => {
                return {
                    value: item.roleId,
                    label: item.roleName,
                    data: item
                };
            });
        }
        if (userInfo.value.roleList && userInfo.value.roleList.length > 0) {
            currentRole.value = userInfo.value.roleList[0];
            currentRoleId.value = userInfo.value.roleList[0].id; // 用户当前角色
            const roleInfo = roleList.value.find(
                (item) => item.value === currentRoleId.value
            );
            if (roleInfo) {
                // 区域角色
                if (
                    userInfo.value.userAreaVOS &&
                    userInfo.value.userAreaVOS.length > 0 &&
                    roleInfo.data.areaList
                ) {
                    roleType.value = 'area';
                    const areaCodes = roleInfo.data.areaList.map(
                        (item) => item.areaCode
                    ); // 当前角色的辖区码列表
                    roleAreaList.value = userInfo.value.userAreaVOS
                        .map((item) => {
                            return {
                                value:
                                    item.gridId ||
                                    item.communityId ||
                                    item.townId ||
                                    item.districtId ||
                                    item.cityId ||
                                    '未知id',
                                data: item,
                                label:
                                    item.gridName ||
                                    item.communityName ||
                                    item.townName ||
                                    item.districtName ||
                                    item.cityName ||
                                    '未知label'
                            };
                        })
                        .filter((item) => {
                            const index = areaCodes.findIndex(
                                (val) => val === item.value
                            );
                            if (index !== -1) {
                                areaCodes.splice(index, 1);
                                return true;
                            }
                            return false;
                        }); // 当前角色的辖区列表
                    const currentGrid = getCurrentGridSync();
                    let storageUserAreaCode = '';
                    if (
                        currentGrid &&
                        currentGrid.roleId &&
                        currentGrid.roleId === currentRoleId.value
                    ) {
                        storageUserAreaCode = currentGrid.areaCode;
                    }
                    const index = roleAreaList.value.findIndex(
                        (item) => item.value === storageUserAreaCode
                    );
                    setUserArea(
                        roleAreaList.value[index === -1 ? 0 : index].data
                    );
                } else if (
                    userInfo.value.departmentVOS &&
                    userInfo.value.departmentVOS.length > 0 &&
                    roleInfo.data.departmentList
                ) {
                    roleType.value = 'depart';
                    // 部门角色
                    const ids = roleInfo.data.departmentList.map(
                        (item) => item.id
                    );
                    roleDeptList.value = userInfo.value.departmentVOS
                        .map((item, index) => {
                            return {
                                value: item.id,
                                data: item,
                                label: item.name || '未知部门'
                            };
                        })
                        .filter((item) => {
                            const index = ids.findIndex(
                                (val) => val === item.value
                            );
                            if (index !== -1) {
                                ids.splice(index, 1);
                                return true;
                            }
                            return false;
                        });
                    const currentDept = getCurrentDeptSync();
                    let storageDepartmentId = -1;
                    if (
                        currentDept &&
                        currentDept.roleId &&
                        currentDept.roleId === currentRoleId.value
                    ) {
                        storageDepartmentId = currentDept.departmentId;
                    }
                    const index = roleDeptList.value.findIndex(
                        (item) => item.value === storageDepartmentId
                    );
                    setUserDepartment(
                        roleDeptList.value[index === -1 ? 0 : index].data
                    );
                }
            }
        }
    };

    // 设置用户当前网格信息
    const setUserArea = (userAreaVo: UserAreaVo) => {
        let gridArr = [];
        currentUserArea.value = userAreaVo;
        gridArr = [
            userAreaVo.cityName,
            userAreaVo.districtName,
            userAreaVo.townName,
            userAreaVo.communityName,
            userAreaVo.gridName
        ];
        if (userAreaVo.districtName) {
            gridArr.shift();
        }
        grid.value = gridArr.filter((it) => it).join('/');
        if (userAreaVo.gridId) {
            currentAreaCode.value = userAreaVo.gridId;
            currentAreaLevel.value = 5;
        } else if (userAreaVo.communityId) {
            currentAreaCode.value = userAreaVo.communityId;
            currentAreaLevel.value = 4;
        } else if (userAreaVo.townId) {
            currentAreaCode.value = userAreaVo.townId;
            currentAreaLevel.value = 3;
        } else if (userAreaVo.districtId) {
            currentAreaCode.value = userAreaVo.districtId;
            currentAreaLevel.value = 2;
        } else if (userAreaVo.cityId) {
            currentAreaCode.value = userAreaVo.cityId;
            currentAreaLevel.value = 1;
        }
        setCurrentGrid({
            ...userAreaVo,
            roleId: currentRoleId.value!,
            areaCode: currentAreaCode.value,
            areaLevel: currentAreaLevel.value!
        });
    };
    // 设置部门用户当前部门信息
    const setUserDepartment = (departmentVo: DepartmentVo) => {
        currentDeptId.value = departmentVo.id;
        currentUserDept.value = departmentVo;
        setCurrentDept({
            ...departmentVo,
            roleId: currentRoleId.value!,
            departmentId: currentDeptId.value!
        });
    };

    const getUserInfo = () => {
        return readMyInfo().then((res) => {
            if (!res) {
                throw new Error('[./store/user]获取用户信息失败');
            }
            setUserInfo(res.data);
            return res;
        });
    };

    const switchRole = async (roleId: number) => {
        await updateRole(roleId);
        await getUserInfo();
    };

    // 后端登出，没有直接调用前端登出
    const logout = async () => {
        await fedLogout();
        return Promise.resolve(true);
    };
    // 前端登出
    const fedLogout = async () => {
        token.value = '';
        hasVaildToken.value = null;
        userInfo.value = undefined;
        removeAccessToken();
        removeUserInfo();
        return Promise.resolve(true);
    };

    return {
        token,
        hasVaildToken,
        userInfo,
        currentRole,
        currentRoleId,
        grid,
        roleList,
        roleAreaList,
        roleDeptList,
        roleType,
        currentUserArea,
        currentUserDept,
        currentAreaCode,
        currentAreaLevel,
        currentDeptId,
        roleFunctions,
        functions,
        login,
        getUserInfo,
        useBackRouteConfig,
        createBackRouteOptionAndGoLogin,
        logout,
        fedLogout,
        setUserArea,
        setUserDepartment,
        switchRole
    };
});

export function useUserStoreHook() {
    return useUserStore(store);
}
